package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    @RequestMapping("/login")
    public R<Employee> login(@RequestBody Employee employee, HttpSession session) {
        R<Employee> login = employeeService.login(employee);
        if (login.getCode() == 1) {
            session.setAttribute("userLogin", login.getData());
        }
        return login;
    }

    @RequestMapping("/logout")
    public R<String> logout(HttpSession session) {
        session.invalidate();
        return R.success(null);
    }

    @PostMapping
    public R<String> save(@RequestBody Employee employee, HttpSession session) {
        Employee userLogin = (Employee) session.getAttribute("userLogin");
        employee.setCreateUser(userLogin.getId());
        employee.setUpdateUser(userLogin.getId());
        employeeService.save(employee);
        return R.success("添加成功");
    }

    @GetMapping("/page")
    public R<Page<Employee>> findByName(Integer page, Integer pageSize, String name) {
        Page<Employee> employeePage = employeeService.findByName(page, pageSize, name);
        return R.success(employeePage);
    }

    @PutMapping
    public R<String> update(@RequestBody Employee employee, HttpSession session) {
        Employee userLogin = (Employee) session.getAttribute("userLogin");
        employee.setUpdateUser(userLogin.getId());
        employeeService.update(employee);
        return R.success("修改成功");
    }

    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable Integer id) {
        Employee employee = employeeService.findById(id);
        return R.success(employee);
    }

}
